<template>

  <div class="app">
    <div style="margin-left: 40px;margin-top: 20px">
      <el-form :inline="true" class="search-form">
        <el-form>
          <el-form-item label="手机号码:">
            <el-input v-model="state.searchCriteria.fkhsjhm" placeholder="请输入号码" style="width: 200px"
                      clearable></el-input>
          </el-form-item>
          <el-form-item label="添加时间:">
            <el-date-picker
              v-model="dateTime"
              type="datetimerange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              :default-time="defaultTime"
              clearable
            />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="state.searchCriteria.fbz" placeholder="请输入关键词" style="width: 200px"
                      clearable></el-input>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="load">
              <el-icon style="vertical-align: middle">
                <Search />
              </el-icon>
              <span style="vertical-align: middle">查询</span>
            </el-button>
            <el-button type="primary" @click="createForm">
              <span style="vertical-align: middle">添加</span>
            </el-button>

          </el-form-item>
        </el-form>
      </el-form>

      <el-table :data="state.tableData" @selection-change="handleSelectionChange" ref="elTableRef">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="fid" label="编号"></el-table-column>
        <el-table-column prop="fkhsjhm" label="黑名单号码"></el-table-column>
        <el-table-column prop="flx" label="添加方式">
          <template v-slot:default="{row}">
            <span v-if="row.flx === '0'">手工导入</span>
            <span v-if="row.flx === '1'">批量导入</span>
          </template>
        </el-table-column>
        <el-table-column prop="fbz" label="备注"></el-table-column>
        <el-table-column prop="fsxsj" label="添加时间"
                         :formatter="row => new Date(row.fsxsj).toLocaleString()"></el-table-column>
        <el-table-column prop="fgqsj" label="有效期"></el-table-column>
        <el-table-column label="操作">
          <template v-slot:default="{row}">
            <el-button type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div style="margin-top: 10px">
        <el-checkbox v-model="selectAll"
                     label="当页全选"
                     size="large"
                     @change="handleSelectAll" />
        <el-button type="primary" style="margin-left: 15px" @click="exportBlacklist">导出黑名单记录</el-button>
        <el-button type="danger" style="margin-left: 15px" @click="handleBatchDelete">批量删除</el-button>
      </div>
    </div>


    <el-dialog v-model="dialogVisible" title="添加外呼黑名单" @close="resetFormData">
      <div style="border-bottom: 1px solid #eee;margin-top: -20px;margin-bottom: 15px"></div>
      <el-form :model="state.formData" ref="formRef" :rules="formRules">
        <el-form-item label="过期时间:">
          <el-input v-model="state.formData.fgqsj" placeholder="单位:天" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="外呼号码:" prop="fkhsjhm">
          <el-input v-model="state.formData.fkhsjhm" type="textarea" :rows="4"
                    placeholder="请输入号码，多个号码请换行"></el-input>
        </el-form-item>
        <div style="margin-left: 80px;margin-top: -15px;margin-bottom: 15px ">共计{{ phoneCount }}个号码</div>
        <el-form-item label="备注:">
          <el-input v-model="state.formData.fbz" placeholder="请输入备注" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="addBlacklist">确定</el-button>
    </span>
    </el-dialog>

    <el-dialog v-model="editDialogVisible" title="编辑外呼黑名单">
      <div style="border-bottom: 1px solid #eee;margin-top: -20px;margin-bottom: 15px"></div>
      <el-form :model="state.editFormData">
        <el-form-item label="过期时间:">
          <el-input v-model="state.editFormData.fgqsj" placeholder="单位:天" style="width: 150px"></el-input>
        </el-form-item>
        <el-form-item label="外呼号码:">
          <el-input v-model="state.editFormData.fkhsjhm" placeholder="请输入号码"></el-input>
        </el-form-item>
        <el-form-item label="备注:">
          <el-input v-model="state.editFormData.fbz" placeholder="请输入备注" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取消</el-button>
    <el-button type="primary" @click="updateBlacklist">确定</el-button>
  </span>
    </el-dialog>


  </div>


</template>

<script setup>
import { computed, onMounted, reactive, ref, watchEffect } from "vue";
import request from "@/utils/request";
import dayjs from "dayjs";
import duration from "dayjs/plugin/duration";
import { ElMessage, ElMessageBox } from "element-plus";

dayjs.extend(duration);

const state = reactive({
  formData: {
    fgqsj: null,
    fkhsjhm: null,
    fbz: null
  },
  editFormData: {
    fid: null,
    fgqsj: null,
    fkhsjhm: null,
    fbz: null
  },
  mumultipleSelection: null,
  tableData: [],
  searchCriteria: {
    fkhsjhm: null,
    fbz: null,
    qssj: null,
    jssj: null
  }
});

const dialogVisible = ref(false);
const editDialogVisible = ref(false);

const dateTime = ref(null);
const defaultTime = [
  new Date(2000, 1, 1, 0, 0, 0),
  new Date(2000, 2, 1, 23, 59, 59)
];

const createForm = () => {
  dialogVisible.value = true;
};


const phoneCount = computed(() => {
  if (!state.formData.fkhsjhm) return 0;
  return state.formData.fkhsjhm.split("\n").length;
});


const load = () => {
  selectAll.value = false;
  request.post("/hmd/find", state.searchCriteria).then(res => {
    state.tableData = res.data;
    console.log(res.data);
  });
};


//定义表单规则
const formRef = ref(null);
const formRules = ref({
  fkhsjhm: [
    {required: true, message: '请输入手机号码', trigger: 'blur'},
  ]
});

const addBlacklist = () => {

  formRef.value.validate((valid) => {
    if (valid){
      // 这里可以调用API来添加黑名单
      console.log(state.formData);
      request.post("/hmd/add", state.formData).then(res => {
        ElMessage({
          type: "success",
          message: "添加成功"
        });
        load();
      }).catch(error => {
        console.log(error);
        ElMessage.error("添加失败");
      });

      resetFormData();
      dialogVisible.value = false;

    }else {
      ElMessage.warning("表单验证失败")
      console.log('表单验证失败');

    }

  })

};

const updateBlacklist = () => {
  // 这里可以调用API来更新黑名单
  console.log(state.editFormData);
  request.post("/hmd/update", state.editFormData).then(res => {
    ElMessage.success("更新成功");
    load();
  }).catch(error => {
      console.log(error);
      ElMessage.error("更新失败");
    }
  );

  editDialogVisible.value = false;
};


const resetFormData = () => {
  state.formData.fgqsj = null;
  state.formData.fkhsjhm = null;
  state.formData.fbz = null;
};

import { useAccount } from "@/pinia/modules/account";

const account = useAccount();


onMounted(() => {
  load();
});


//监听dateTime的变化
watchEffect(() => {
  if (dateTime.value) {
    state.searchCriteria.qssj = dateTime.value[0];
    state.searchCriteria.jssj = dateTime.value[1];
  } else {
    state.searchCriteria.qssj = undefined;
    state.searchCriteria.jssj = undefined;
  }
});


//编辑
const handleEdit = (row) => {
  state.editFormData = { ...row }; // 复制选中行的数据到formData
  editDialogVisible.value = true; // 打开对话框
};


//删除
const handleDelete = (row) => {
  // 显示确认对话框
  ElMessageBox.confirm("确定删除该记录吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {

    request.post("/hmd/del/" + row.fid).then(res => {

      ElMessage.success("删除成功");
      load();
    }).catch(error => {
      console.log(error);
      ElMessage.error("删除失败");
    });

  });
};


//多选框
const handleSelectionChange = (val) => {
  state.multipleSelection = val;
  selectAll.value = state.tableData.length && val.length === state.tableData.length;
};


//全选功能
const elTableRef = ref(null);
const selectAll = ref(false);
const handleSelectAll = () => {
  elTableRef.value.clearSelection(); // 先清除所有的选择
  if (selectAll.value) {
    elTableRef.value.toggleAllSelection(); // 如果是全选状态，则全选所有行
  }
};


//批量删除
const clearSelection = () => {
  state.multipleSelection = [];
  selectAll.value = false;
};

const handleBatchDelete = () => {
  if (!state.multipleSelection.length) {
    ElMessage.warning("请至少选择一条记录");
    return;
  }

  // 显示确认对话框
  ElMessageBox.confirm("确定删除所选记录吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    const ids = state.multipleSelection.map(item => item.fid);

    request.post("/hmd/del/batchDelete", ids)
      .then(res => {
        ElMessage.success("批量删除成功");
        clearSelection();
        load(); // 重新加载表格数据
      })
      .catch(err => {
        console.error(err);
        ElMessage.error("批量删除失败");
      });
  });
};

// 导出黑名单
const exportBlacklist = () => {
  window.open("http://localhost:9000/hmd/export");
};


</script>

<style>

</style>